import { defineStore } from 'pinia'
import { getNextPuzzle, submitAnswer, recordAction, getUserAnswers, saveProgress, getProgress } from '../api/game'
import { showToast } from 'vant'

export const useGameStore = defineStore('game', {
  state: () => ({
    // 当前游戏信息
    currentGame: {
      id: null,
      level: 'easy',
      board: Array(9).fill().map(() => Array(9).fill(0)),
      solution: Array(9).fill().map(() => Array(9).fill(0)),
      original: Array(9).fill().map(() => Array(9).fill(0)), // 初始盘面（不可修改的数字）
      startTime: null,
      endTime: null,
      isComplete: false,
      userId: null // 添加用户ID字段
    },
    // 游戏设置
    settings: {
      showErrors: true,
      showTimer: true,
      highlightSameNumbers: true
    },
    // 游戏状态
    gameState: {
      isPlaying: false,
      isPaused: false,
      elapsedTime: 0,
      mistakes: 0,
      hintsUsed: 0
    },
    // 选中的单元格
    selectedCell: {
      row: -1,
      col: -1
    }
  }),
  
  getters: {
    // 当前游戏时间（秒）
    currentTime: (state) => {
      if (!state.currentGame.startTime) return 0
      if (state.currentGame.endTime) {
        return Math.floor((state.currentGame.endTime - state.currentGame.startTime) / 1000)
      }
      return state.gameState.elapsedTime
    },
    
    // 游戏是否完成
    isGameComplete: (state) => state.currentGame.isComplete,
    
    // 单元格是否为原始数字（不可修改）
    isOriginal: (state) => (row, col) => state.currentGame.original[row][col] !== 0,
    
    // 获取单元格值
    getCellValue: (state) => (row, col) => state.currentGame.board[row][col],
    
    // 检查单元格是否有冲突
    hasConflict: (state) => (row, col) => {
      const value = state.currentGame.board[row][col]
      if (value === 0) return false
      
      // 检查行
      for (let c = 0; c < 9; c++) {
        if (c !== col && state.currentGame.board[row][c] === value) {
          return true
        }
      }
      
      // 检查列
      for (let r = 0; r < 9; r++) {
        if (r !== row && state.currentGame.board[r][col] === value) {
          return true
        }
      }
      
      // 检查3x3方格
      const startRow = Math.floor(row / 3) * 3
      const startCol = Math.floor(col / 3) * 3
      
      for (let r = startRow; r < startRow + 3; r++) {
        for (let c = startCol; c < startCol + 3; c++) {
          if (r !== row && c !== col && state.currentGame.board[r][c] === value) {
            return true
          }
        }
      }
      
      return false
    },
    
    // 是否选中单元格
    isSelected: (state) => (row, col) => {
      return state.selectedCell.row === row && state.selectedCell.col === col
    },
    
    // 单元格是否与选中单元格共享行、列或3x3方格
    isRelated: (state) => (row, col) => {
      if (state.selectedCell.row === -1 || state.selectedCell.col === -1) return false
      
      const selectedRow = state.selectedCell.row
      const selectedCol = state.selectedCell.col
      
      // 同行或同列
      if (row === selectedRow || col === selectedCol) return true
      
      // 同一3x3方格
      const selectedBox = Math.floor(selectedRow / 3) * 3 + Math.floor(selectedCol / 3)
      const cellBox = Math.floor(row / 3) * 3 + Math.floor(col / 3)
      
      return selectedBox === cellBox
    },
    
    // 单元格是否与选中单元格有相同的值
    hasSameValue: (state) => (row, col) => {
      if (state.selectedCell.row === -1 || state.selectedCell.col === -1) return false
      
      const selectedValue = state.currentGame.board[state.selectedCell.row][state.selectedCell.col]
      const cellValue = state.currentGame.board[row][col]
      
      return selectedValue !== 0 && selectedValue === cellValue
    }
  },
  
  actions: {
    // 新游戏
    async newGame(level = 'easy', userId) {
      try {
        let gameData
        
        if (userId) {
          // 从服务器获取下一个游戏题目
          const res = await getNextPuzzle({ userId, level })
          if (res.code === 0) {
            gameData = {
              id: res.data.id,
              puzzle: this.stringToBoard(res.data.puzzle),
              solution: this.stringToBoard(res.data.solution)
            }
          } else {
            throw new Error(res.message || '获取游戏数据失败')
          }
        } else {
          throw new Error('需要提供用户ID')
        }
        
        // 重置游戏状态
        this.currentGame = {
          id: gameData.id || null,
          level,
          board: JSON.parse(JSON.stringify(gameData.puzzle)),
          solution: JSON.parse(JSON.stringify(gameData.solution)),
          original: JSON.parse(JSON.stringify(gameData.puzzle)),
          startTime: Date.now(),
          endTime: null,
          isComplete: false,
          userId: userId // 保存用户ID
        }
        
        this.gameState = {
          isPlaying: true,
          isPaused: false,
          elapsedTime: 0,
          mistakes: 0,
          hintsUsed: 0
        }
        
        this.selectedCell = {
          row: -1,
          col: -1
        }
        
        return true
      } catch (error) {
        console.error('创建新游戏失败', error)
        // 重新抛出错误，让调用方能够获取具体错误信息
        throw error
      }
    },
    
    // 暂存游戏
    async saveCurrentGame() {
      if (!this.currentGame.id || !this.currentGame.userId) {
        console.warn('缺少游戏ID或用户ID，无法保存进度')
        return false
      }
      
      try {
        const progressData = {
          userId: this.currentGame.userId,
          puzzleId: this.currentGame.id,
          answer: this.boardToString(this.currentGame.board),
          timeUsed: this.gameState.elapsedTime,
          mistakes: this.gameState.mistakes,
          hintsUsed: this.gameState.hintsUsed
        }
        
        const res = await saveProgress(progressData)
        
        if (res.code === 0) {
          console.log('游戏进度保存成功')
          return true
        } else {
          console.error('保存游戏进度失败:', res.message)
          return false
        }
      } catch (error) {
        console.error('保存游戏失败', error)
        return false
      }
    },

    // 加载游戏进度
    async loadProgress(userId, puzzleId) {
      try {
        const res = await getProgress({ userId, puzzleId })
        
        if (res.code === 0 && res.data) {
          const progress = res.data
          
          // 设置游戏数据
          this.currentGame = {
            id: progress.puzzleId,
            level: progress.puzzle.level,
            board: this.stringToBoard(progress.currentBoard),
            solution: this.stringToBoard(progress.puzzle.solution),
            original: this.stringToBoard(progress.puzzle.puzzle),
            startTime: new Date(progress.startedAt).getTime(),
            endTime: null,
            isComplete: false,
            userId: progress.userId
          }

          this.gameState = {
            isPlaying: true,
            isPaused: false,
            elapsedTime: progress.timeUsed || 0,
            mistakes: progress.mistakes || 0,
            hintsUsed: progress.hintsUsed || 0
          }

          this.selectedCell = {
            row: -1,
            col: -1
          }

          return true
        } else {
          return false
        }
      } catch (error) {
        console.error('加载游戏进度失败', error)
        return false
      }
    },
    
    // 设置单元格的值
    setCellValue(row, col, value) {
      // 如果是原始数字，不可修改
      if (this.isOriginal(row, col)) return false
      
      this.currentGame.board[row][col] = value
      
      // 检查是否有冲突
      if (value !== 0 && this.hasConflict(row, col)) {
        this.gameState.mistakes++
      }
      
      // 检查游戏是否完成
      this.checkGameComplete()
      
      return true
    },
    
    // 设置选中的单元格
    selectCell(row, col) {
      this.selectedCell = { row, col }
    },
    
    // 清除选中的单元格
    clearSelection() {
      this.selectedCell = { row: -1, col: -1 }
    },
    
    // 暂停游戏
    pauseGame() {
      if (this.gameState.isPlaying && !this.gameState.isPaused) {
        this.gameState.isPaused = true
        // 记录当前游戏时长
        this.updateElapsedTime()
      }
    },
    
    // 恢复游戏
    resumeGame() {
      if (this.gameState.isPlaying && this.gameState.isPaused) {
        this.gameState.isPaused = false
      }
    },
    
    // 更新用时
    updateElapsedTime() {
      if (!this.currentGame.startTime || this.currentGame.endTime) return
      
      const now = Date.now()
      this.gameState.elapsedTime = Math.floor((now - this.currentGame.startTime) / 1000)
    },
    
    // 获取提示
    async getGameHint() {
      // 如果提示次数大于等于3，不提供更多提示
      if (this.gameState.hintsUsed >= 3){
        showToast('提示次数已达上限')
        return false
      } 

      if (this.selectedCell.row === -1 || this.selectedCell.col === -1) {
        return false
      }
      
      const row = this.selectedCell.row
      const col = this.selectedCell.col
      
      // 如果是原始数字或已有值，不提供提示
      if (this.isOriginal(row, col) || this.currentGame.board[row][col] !== 0) {
        return false
      }
      
      try {
        let hintData = {
            row,
            col,
            value: this.currentGame.solution[row][col]
          }
        
        // 设置单元格的值
        this.currentGame.board[row][col] = hintData.value
        
        // 增加使用提示次数
        this.gameState.hintsUsed++
        
        // 检查游戏是否完成
        this.checkGameComplete()
        
        return true
      } catch (error) {
        console.error('获取提示失败', error)
        return false
      }
    },
    
    // 检查游戏是否完成
    async checkGameComplete() {
      // 检查是否填满并有效
      if (this.isSolved(this.currentGame.board)) {
        this.currentGame.isComplete = true
        this.currentGame.endTime = Date.now()
        this.gameState.isPlaying = false
        
        // 更新最终游戏时长
        this.updateElapsedTime()
        
        // 提交完成记录到后端
        if (this.currentGame.id && this.currentGame.userId) {
          try {
            const submitData = {
              userId: this.currentGame.userId,
              puzzleId: this.currentGame.id,
              answer: this.boardToString(this.currentGame.board),
              timeUsed: this.gameState.elapsedTime
            }
            
            const result = await submitAnswer(submitData)
            
            if (result.code === 0) {
              console.log('答案提交成功:', result.data)
            } else {
              console.error('答案提交失败:', result.message)
            }
          } catch (error) {
            console.error('提交答案时发生错误:', error)
          }
        }
        
        return true
      }
      
      return false
    },
    
    // 重置当前游戏
    resetGame() {
      if (!this.currentGame.id) return
      
      this.currentGame.board = JSON.parse(JSON.stringify(this.currentGame.original))
      this.currentGame.endTime = null
      this.currentGame.isComplete = false
      
      this.gameState.isPlaying = true
      this.gameState.isPaused = false
      this.gameState.mistakes = 0
      this.gameState.hintsUsed = 0
      
      this.selectedCell = { row: -1, col: -1 }
    },

    // 加载游戏数据
    async loadGame(question) {
      try {
        // 设置游戏数据
        this.currentGame = {
          id: question.id,
          level: question.level,
          board: JSON.parse(JSON.stringify(question.currentBoard || question.puzzle)),
          solution: JSON.parse(JSON.stringify(question.solution)),
          original: JSON.parse(JSON.stringify(question.puzzle)),
          startTime: question.startTime ? new Date(question.startTime).getTime() : Date.now(),
          endTime: question.endTime ? new Date(question.endTime).getTime() : null,
          isComplete: question.isComplete || false,
          userId: question.userId || null // 添加用户ID
        }

        this.gameState = {
          isPlaying: !question.isComplete,
          isPaused: false,
          elapsedTime: question.elapsedTime || 0,
          mistakes: question.mistakes || 0,
          hintsUsed: question.hintsUsed || 0
        }

        this.selectedCell = {
          row: -1,
          col: -1
        }

        return true
      } catch (error) {
        console.error('加载游戏失败', error)
        return false
      }
    },

    // 辅助方法：将字符串转换为9x9棋盘
    stringToBoard(str) {
      const board = Array(9).fill().map(() => Array(9).fill(0))
      for (let i = 0; i < 81; i++) {
        const row = Math.floor(i / 9)
        const col = i % 9
        board[row][col] = parseInt(str[i]) || 0
      }
      return board
    },

    // 辅助方法：将9x9棋盘转换为字符串
    boardToString(board) {
      let str = ''
      for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
          str += board[i][j].toString()
        }
      }
      return str
    },

    // 辅助方法：检查数独是否完成
    isSolved(board) {
      // 检查是否填满
      for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
          if (board[i][j] === 0) {
            return false
          }
        }
      }

      // 检查行、列、9宫格是否有效
      for (let i = 0; i < 9; i++) {
        // 检查行
        const rowSet = new Set()
        for (let j = 0; j < 9; j++) {
          if (rowSet.has(board[i][j])) return false
          rowSet.add(board[i][j])
        }

        // 检查列
        const colSet = new Set()
        for (let j = 0; j < 9; j++) {
          if (colSet.has(board[j][i])) return false
          colSet.add(board[j][i])
        }
      }

      // 检查9宫格
      for (let box = 0; box < 9; box++) {
        const boxSet = new Set()
        const startRow = Math.floor(box / 3) * 3
        const startCol = (box % 3) * 3

        for (let i = 0; i < 3; i++) {
          for (let j = 0; j < 3; j++) {
            const val = board[startRow + i][startCol + j]
            if (boxSet.has(val)) return false
            boxSet.add(val)
          }
        }
      }

      return true
    }
  }
})
